﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace TLC
{
    public partial class ImageWnd : Form
    {
        public ImageWnd()
        {
            InitializeComponent();
        }

        public void SetFIBitmap(FreeImageAPI.FIBITMAP bitmap)
        {
            this._bitmap = bitmap;
        }

        public FreeImageAPI.FIBITMAP GetFIBitmap()
        {
            return this._bitmap;
        }

        public void SetScale(int type/*0:窗口大小，1图片原始大小，2缩放*/, double value)
        {
            this._scaleType = type;
            this._scaleValue = value;
        }

        private void ImageWnd_Paint(object sender, PaintEventArgs e)
        {
            if (!this._bitmap.IsNull)
            {
                FreeImageAPI.FIBITMAP bmp = this._bitmap;

                IntPtr pBits = FreeImageAPI.FreeImage.GetBits(bmp);
                IntPtr pIf = FreeImageAPI.FreeImage.GetInfo(bmp);
                
                uint width = FreeImageAPI.FreeImage.GetWidth(bmp);
                uint height = FreeImageAPI.FreeImage.GetHeight(bmp);
                uint toWidth = width;
                uint toHeight= height;

                IntPtr hdc = e.Graphics.GetHdc();

                switch (this._scaleType)
                {
                    case 0:
                        toWidth = Convert.ToUInt32(this.Size.Width);
                        toHeight = Convert.ToUInt32(this.Size.Height);
                        break;
                    case 1:
                        toWidth = width;
                        toHeight = height;
                        break;
                    case 2:
                        toWidth = Convert.ToUInt32(width * this._scaleValue);
                        toHeight = Convert.ToUInt32(height * this._scaleValue);
                        break;
                    default:
                        break;
                }

                Gdi32.Bitmaps.SetStretchBltMode(hdc, 3);

                if (toWidth == width && toHeight == height)
                {
                    Gdi32.Bitmaps.SetDIBitsToDevice(e.Graphics.GetHdc(), 0, 0, width, height, 0, 0, 0, height, pBits, pIf, 0);
                }
     	        else 
     	        {
                    Gdi32.Bitmaps.StretchDIBits(hdc, 0, 0, toWidth, toHeight, 0, 0, width, height, pBits, pIf, 0, 0x00CC0020);
     	        }
            }
        }
        
        private FreeImageAPI.FIBITMAP _bitmap;
        int     _scaleType;
        double  _scaleValue;
    }
}